package org.bonorsoft.modules.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.bonorsoft.common.constant.CommonConstant;
import org.bonorsoft.common.constant.UserConstants;
import org.bonorsoft.common.exception.WilliamBootException;
import org.bonorsoft.common.system.vo.Ztree;
import org.bonorsoft.common.util.StringUtils;
import org.bonorsoft.common.util.oConvertUtils;
import org.bonorsoft.modules.mobile.service.IMobileUserService;
import org.bonorsoft.modules.mobileutils.login.MobileLoginInfo;
import org.bonorsoft.modules.user.entity.MobileDepart;
import org.bonorsoft.modules.user.entity.MobileRole;
import org.bonorsoft.modules.user.mapper.MobileDepartMapper;
import org.bonorsoft.modules.user.mapper.MobileRoleDeptMapper;
import org.bonorsoft.modules.user.service.IMobileDepartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 组织结构
 */

@Service
public class MobileDepartServiceImpl extends ServiceImpl<MobileDepartMapper, MobileDepart> implements IMobileDepartService {
    @Autowired
    private IMobileUserService userService;

    @Resource
    private MobileRoleDeptMapper roleDeptMapper;

    @Override
    public void deleteDepart(List<Integer> deptId) {
        this.removeByIds(deptId);
    }

    /**
     * 查询部门管理树
     *
     * @param dept 部门信息
     * @param req
     * @return 所有部门信息
     */
    @Override
    public List<Ztree> selectDeptTree(MobileDepart dept, HttpServletRequest req) {
        List<MobileDepart> deptList = selectDeptList(dept, req);
        List<Ztree> ztrees = initZtree(deptList);
        return ztrees;
    }


    @Override
    public List<MobileDepart> queryUserDeparts(String userid) {
        return baseMapper.queryUserDeparts(userid);
    }

    /**
     * 根据角色ID查询部门（数据权限）
     *
     * @param role    角色对象
     * @param request
     * @return 部门列表（数据权限）
     */
    @Override
    public List<Ztree> roleDeptTreeData(MobileRole role, HttpServletRequest request) {
        Integer id = role.getId();
        List<Ztree> ztrees;
        List<MobileDepart> deptList = selectDeptList(new MobileDepart(), request);
        if (StringUtils.isNotNull(id)) {
            List<String> roleDeptList = roleDeptMapper.selectRoleDeptTree(id);
            ztrees = initZtree(deptList, roleDeptList);
        } else {
            ztrees = initZtree(deptList);
        }
        return ztrees;
    }

    @Override
    public MobileDepart getDepartNameById(Long deptId) {
        return this.getById(deptId);
    }

    /**
     * 对象转部门树
     *
     * @param deptList 部门列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<MobileDepart> deptList) {
        return initZtree(deptList, null);
    }

    /**
     * 对象转部门树
     *
     * @param deptList     部门列表
     * @param roleDeptList 角色已存在菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<MobileDepart> deptList, List<String> roleDeptList) {

        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleDeptList);
        for (MobileDepart dept : deptList) {

            Ztree ztree = new Ztree();
            ztree.setId(dept.getDeptId());
            ztree.setpId(dept.getParentId());
            ztree.setName(dept.getDeptName());
            ztree.setTitle(dept.getDeptName());
            if (isCheck) {
                ztree.setChecked(roleDeptList.contains(dept.getDeptId() + dept.getDeptName()));
            }
            ztrees.add(ztree);

        }
        return ztrees;
    }

    /**
     * 获取全部部门
     *
     * @param dept
     * @param req
     * @return
     */
    private List<MobileDepart> selectDeptList(MobileDepart dept, HttpServletRequest req) {
        QueryWrapper<MobileDepart> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("order_num");
        String sql = (String) req.getAttribute(CommonConstant.DATA_SCOPE);
        if (oConvertUtils.isNotEmpty(sql)) {
            queryWrapper.apply(sql);
        }
        return this.list(queryWrapper);
    }

    /**
     * 查询部门人数
     *
     * @param parentId 部门ID
     * @return 结果
     */
    @Override
    public int selectDeptCount(Long parentId) {
        QueryWrapper<MobileDepart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", "0")
                .eq("parent_id", parentId);
        return this.count(queryWrapper);
    }


    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId) {
        int result = userService.checkDeptExistUser(deptId);
        return result > 0;
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return
     */
    @Override
    public String checkDeptNameUnique(MobileDepart dept) {
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        MobileDepart info = checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue()) {
            return UserConstants.DEPT_NAME_NOT_UNIQUE;
        }
        return UserConstants.DEPT_NAME_UNIQUE;
    }

    /**
     * 获取部门信息
     *
     * @param deptName
     * @param parentId
     * @return
     */
    private MobileDepart checkDeptNameUnique(String deptName, Long parentId) {
        return this.getOne(new QueryWrapper<MobileDepart>().eq("dept_name", deptName).eq("parent_id", parentId));
    }

    /**
     * 重写添加逻辑
     *
     * @param sysDepart
     * @return
     */
    @Override
    public boolean save(MobileDepart sysDepart) {
        MobileDepart info = this.getById(sysDepart.getParentId());
        // 如果父节点不为"正常"状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new WilliamBootException("部门停用，不允许新增");
        }
        sysDepart.setAncestors(info.getAncestors() + "," + sysDepart.getParentId());
        sysDepart.setCreateBy(MobileLoginInfo.getLoginUser().getUsername());
        sysDepart.setCreateTime(new Date());
        return retBool(baseMapper.insert(sysDepart));
    }

    /**
     * 修改部门信息
     *
     * @param sysDepart
     */
    @Override
    @Transactional
    public boolean updateDept(MobileDepart sysDepart) {
        MobileDepart newParentDept = getDepartNameById(sysDepart.getParentId());
        MobileDepart oldDept = getDepartNameById(sysDepart.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            sysDepart.setAncestors(newAncestors);
            updateDeptChildren(sysDepart.getDeptId(), newAncestors, oldAncestors);
        }

        sysDepart.setUpdateBy(MobileLoginInfo.getLoginUser().getUsername());
        sysDepart.setUpdateTime(new Date());
        boolean res = retBool(baseMapper.updateById(sysDepart));
        if (UserConstants.DEPT_NORMAL.equals(sysDepart.getStatus())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            oldDept.setUpdateBy(sysDepart.getUpdateBy());
            updateParentDeptStatus(oldDept);
        }
        return res;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatus(MobileDepart dept) {
        baseMapper.updateDeptStatus(dept);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    private void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<MobileDepart> children = baseMapper.selectChildrenDeptById(deptId);
        for (MobileDepart child : children) {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            baseMapper.updateDeptChildren(children);
        }
    }
}
